#!/bin/bash
# deployment_script.sh 文件介绍

## 1. 脚本用途
# 用于批量部署或删除指定脚本到匹配目录中，支持以下操作：
# - `deploy`：将脚本复制到匹配目录
# - `remove`：从匹配目录中删除脚本

## 2. 参数说明
# usage: deployment_script.sh [OPERATION] [DIRECTORY_PREFIX] [SCRIPT_NAME]
# - OPERATION：操作类型，支持 `deploy` 或 `remove`
# - DIRECTORY_PREFIX：匹配目录的前缀
# - SCRIPT_NAME：要部署或删除的脚本名称
# - 例如：./deployment_script.sh deploy 2025 bag_player.sh

# 将操作类型作为变量获取
operation="$1"

# 将目录名称作为变量获取
directory_prefix="$2"

# 将脚本名称作为变量获取
script_name="$3"

echo "Received parameters: op=$operation, dir_prefix=$directory_prefix, script=$script_name"

source_path="/mnt/HDD/home/ubuntu/BAG/$script_name"
if [ ! -e "$source_path" ]; then
    echo "Source file not found: $source_path"
    exit 1
fi

# 检查是否提供了操作类型
if [ -z "$operation" ]; then
    echo "Please provide the operation type -->"
    exit 1
fi

# 检查是否提供了目录信息
if [ -z "$directory_prefix" ]; then
    echo "Please provide the directory information to operate on -->"
    exit 1
fi

if [ "$operation" = "deploy" ]; then
    echo "Start looping through directories and copying files"
    # 循环匹配目录并复制文件
    for dir in "$directory_prefix"*; do
        if [ -d "$dir" ]; then
            echo "Copying files to directory: $dir"
            if [ -e "$dir/$script_name" ]; then
                echo "File already exists: $dir/$script_name"
            else
                cp /mnt/HDD/home/ubuntu/BAG/$script_name "$dir"
            fi
        fi
    done

    echo "Deployment completed"
elif [ "$operation" = "remove" ]; then
    echo "Start looping through directories and deleting files"
    # 循环匹配目录并复制或删除文件
    for dir in "$directory_prefix"*; do
        if [ -d "$dir" ]; then
            # 检查是否存在脚本文件，如果存在则删除，否则复制
            if [ -e "$dir/$script_name" ]; then
                rm "$dir/$script_name"
                echo "Deleted $script_name in $dir"
            else
                echo "$script_name not found in $dir, no need to delete"
            fi
        fi
    done
else
    echo "Invalid operation type: $operation"
    exit 1
fi
